package v1

import (
	"github.com/gin-gonic/gin"
	"maya-service/bll"
	"maya-service/model"
	"maya-service/server/web/middleware"
	"maya-service/utils"
)

var SysUsers = &sysUsers{}

func init() {
	RegisterRouter(SysUsers)
}

type sysUsers struct{}

// Init
func (a *sysUsers) Init(r *gin.RouterGroup) {
	g := r.Group("/sysUsers", middleware.Auth())
	{
		g.POST("/create", a.create)
		g.POST("/update", a.update)
		g.POST("/list", a.list)
		g.POST("/delete", a.delete)
		g.POST("/detail", a.find)
	}
}

// create
func (a *sysUsers) create(c *gin.Context) {
	var (
		in  = &model.SysUsersCreateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.SysUsers.Create(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// update
func (a *sysUsers) update(c *gin.Context) {
	var (
		in  = &model.SysUsersUpdateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	// 修改密码
	if in.Password != nil && in.OldPassword != nil {
		// 校验旧密码
		oldPassword := utils.BcryptHash(*in.OldPassword)

		password := utils.BcryptHash(*in.Password)
		in.Password = &password

		params := &model.SysUsersInfoRequest{}
		if in.Username != nil {
			params.UserName = *in.Username
		}

		if in.Uuid != nil {
			params.UserId = *in.Uuid
		}

		find, _ := bll.SysUsers.Find(c.Request.Context(), params)
		if find != nil && find.Id > 0 {
			if find.Password != oldPassword {
				utils.ResponseOkWithError(c, "修改失败，旧密码错误")
				return
			}
			in.Id = find.Id
		}
	}

	if in.Id <= 0 {
		utils.ResponseOkWithError(c, "修改失败，需要Id")
		return
	}

	if err = bll.SysUsers.Update(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// list
func (a *sysUsers) list(c *gin.Context) {
	var (
		in  = &model.SysUsersListRequest{}
		out = &model.SysUsersListResponse{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.SysUsers.List(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, out)
}

// list
func (a *sysUsers) find(c *gin.Context) {
	var (
		in  = &model.SysUsersInfoRequest{}
		out = &model.SysUsersInfo{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.SysUsers.Find(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, out)
}

// delete
func (a *sysUsers) delete(c *gin.Context) {
	var (
		in  = &model.SysUsersDeleteRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.SysUsers.Delete(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}
